package com.cjzuji.rental.regular;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.mapper.RequestMapper;
import com.cjzuji.rental.mapper.RiskApprovilMapper;
import com.cjzuji.rental.pojo.MultiPlatfromResult;
import com.cjzuji.rental.pojo.RequestHeard;
import com.cjzuji.rental.pojo.RiskApprovil;
import com.cjzuji.rental.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.channels.MulticastChannel;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

//@RestController
@Component
public class RunRegular {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    RequestMapper requestMapper;
    @Autowired
    AiDouService aiDouService;
    @Autowired
    YouPinService youPinService;
    @Autowired
    QianLianYPService qianLianYPService;
    @Autowired
    ErSQLYPService erSQLYPService;
    @Autowired
    RenRZuService renRZuService;
    @Autowired
    ErSRRZService erSRRZService;
    @Autowired
    LingLService lingLService;
    @Autowired
    GCLingLService gCLingLService;
    @Autowired
    AiZuJiService aizujiService;
    @Autowired
    ChangJiuAZJService changJiuAZJService;
    @Autowired
    WenShiAZJService wenShiAZJService;
    @Autowired
    XWuService xWuService;
    @Autowired
    WsErYpService wsErYpService;
    @Autowired
    YpRiskService ypRiskService;
    @Autowired
    RiskApprovilMapper riskApprovilMapper;
    private static final Logger logger = LoggerFactory.getLogger(RunRegular.class);
    //http://127.0.0.1:9099/order/aiDou/getQzjInfo
    //@Scheduled(fixedRate = 60 * 60 * 2000)
    //@Scheduled(cron = "0 0 0/2 * * ?")  //每2小时执行一次
    public MultiPlatfromResult getAllPlatformInfo() {
        MultiPlatfromResult result = new MultiPlatfromResult();
        //从数据库获取
        QueryWrapper<RequestHeard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", 1);
        RequestHeard requestHeard = requestMapper.selectOne(queryWrapper);
        String accesstoken = requestHeard.getAccesstoken();
        String authorization = requestHeard.getAuthorization();
        String aidAccesstoken = requestHeard.getAidaccesstoken();
        String qLYPAccesstoken = requestHeard.getQlypaccesstoken();
        String qLYPAuthorization = requestHeard.getQlypauthorization();
        String erSQLYPAccesstoken = requestHeard.getErsqlypaccesstoken();
        String erSQLYPAuthorization = requestHeard.getErsqlypauthorization();
        String wsErYPAccesstoken = requestHeard.getWserypaccesstoken();
        String wsErYPAuthorization = requestHeard.getWserypauthorization();
        String xWuCookie = requestHeard.getXwucookie() ;
        String xWuToken = requestHeard.getXwutoken();
        String xWuRandomCode = requestHeard.getXwurandomCode();
        logger.info("开始同步四个平台所有数据...");
        //使用CompletableFuture实现多线程
        CompletableFuture<Object> youPinFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("同步优品平台所有数据...");
            return youPinService.getOrderssList(accesstoken, authorization);
        });
        CompletableFuture<Object> aiDouFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("同步爱豆平台所有数据...");
            return aiDouService.getAiDList(aidAccesstoken);
        });
        CompletableFuture<Object> qianLianYPFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("同步谦莲优品平台所有数据...");
            return qianLianYPService.getOrderssList(erSQLYPAccesstoken, qLYPAuthorization);
        });
        CompletableFuture<Object> erSQLYPFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("同步二手谦莲优品平台所有数据...");
            return erSQLYPService.getOrderssList(qLYPAccesstoken, erSQLYPAuthorization);
        });
        CompletableFuture<Object> xWuFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("同步X物平台所有数据...");
            return xWuService.getOrdersList(xWuToken, xWuCookie,xWuRandomCode);
        });
        CompletableFuture<Object> wsYpErFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("同步 稳实优品二店 平台所有数据...");
            return wsErYpService.getOrderssList(wsErYPAccesstoken, wsErYPAuthorization);
        });

        //等待所有任务完成
        try {
            CompletableFuture.allOf(youPinFuture, aiDouFuture, qianLianYPFuture,erSQLYPFuture,xWuFuture,wsYpErFuture).get(6, TimeUnit.MINUTES);
            result.setYouPinResult((List<Map<String, Object>>) youPinFuture.get());
            result.setAiDouResult((List<Map<String, Object>>) aiDouFuture.get());
            result.setQianLianYPResult((List<Map<String, Object>>) qianLianYPFuture.get());
            result.setErSQLYPResult((List<Map<String, Object>>) erSQLYPFuture.get());
            result.setXWuResult((List<Map<String, Object>>) xWuFuture.get());
            result.setWsErYPResult((List<Map<String, Object>>) wsYpErFuture.get());
        }catch (Exception e){
            logger.error("获取数据时发生异常~~~~~~~~~~~~", e);
        }
        return result;
    }

    //获取租用中的数据和更新逾期 数据
    //@Scheduled(fixedRate = 60 * 60 * 24000)
    //每晚上6点执行一次
    //@Scheduled(cron = "0 0 18 * * ?")
    //@Scheduled(cron = "0 0 0 * * ?")  //每天0点执行一次
    public MultiPlatfromResult upDateBill(){
        MultiPlatfromResult result = new MultiPlatfromResult();
        //从数据库获取
        QueryWrapper<RequestHeard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",1);
        RequestHeard requestHeard = requestMapper.selectOne(queryWrapper);
        String accesstoken = requestHeard.getAccesstoken();
        String authorization = requestHeard.getAuthorization();
        String aidAccesstoken = requestHeard.getAidaccesstoken();
        String qLYPAccesstoken = requestHeard.getQlypaccesstoken();
        String qLYPAuthorization = requestHeard.getQlypauthorization();
        String erSQLYPAccesstoken = requestHeard.getErsqlypaccesstoken();
        String erSQLYPAuthorization = requestHeard.getErsqlypauthorization();
        String cookie = requestHeard.getCookie();
        String renRZAuthorization = requestHeard.getRrzauthorization();
        String ersRRZCookie = requestHeard.getErsrrzcookie();
        String ersRRZAuthorization = requestHeard.getErsrrzauthorization();
        String lLCookie = requestHeard.getLinglcookie();
        String lingLToken = requestHeard.getLingltoken();
        String gCLLCookie = requestHeard.getGclinglcookie();
        String gCLLToken = requestHeard.getGclingltoken();
        String aizjtk = requestHeard.getAzjtk();
        String cJAZJtk = requestHeard.getCjazjtk();
        String wsAZJtk = requestHeard.getWsazjtk();
        logger.info("开始更新9个平台租用中数据...");
        //使用CompletableFuture实现多线程
        CompletableFuture<Object> youPinFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新优品平台租用中数据...");
            return youPinService.upDateBillList(accesstoken, authorization, "useList");
        });
        CompletableFuture<Object> aiDouFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新爱豆平台租用中数据...");
            return aiDouService.upDateBillList(aidAccesstoken);
        });
        CompletableFuture<Object> qianLianYPFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新谦莲优品平台租用中数据...");
            return qianLianYPService.upDateBillList(qLYPAccesstoken, qLYPAuthorization, "useList");
        });
        CompletableFuture<Object> erSYPFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新二手优品平台租用中数据...");
            return erSQLYPService.upDateBillList(erSQLYPAccesstoken, erSQLYPAuthorization, "useList");
        });
        CompletableFuture<Object> renRZFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新人人租平台租用中数据...");
            return renRZuService.upDateBillList(renRZAuthorization, cookie);
        });
        CompletableFuture<Object> erSRRZFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新二手人人租平台租用中数据...");
            return erSRRZService.upDateBillList(ersRRZCookie, ersRRZAuthorization);
        });
        CompletableFuture<Object> lLFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新零零平台租用中数据...");
            return lingLService.upDateBillList(lLCookie, lingLToken);
        });
        CompletableFuture<Object> gCLingLFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新广创零零平台租用中数据...");
            return gCLingLService.upDateBillList(gCLLCookie, gCLLToken);
        });
        CompletableFuture<Object> aiZJLingLFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新爱租机平台租用中数据...");
            return aizujiService.upDateBill(aizjtk);
        });
        CompletableFuture<Object> cJAZJFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新长久爱租机平台租用中数据...");
            return changJiuAZJService.upDateBill(cJAZJtk);
        });
        CompletableFuture<Object> wenShiAZJFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("更新稳实爱租机平台租用中数据...");
            return wenShiAZJService.upDateBill(wsAZJtk);
        });
        try {
            CompletableFuture.allOf(youPinFuture, aiDouFuture, qianLianYPFuture, erSYPFuture, renRZFuture, erSRRZFuture, lLFuture, gCLingLFuture, aiZJLingLFuture, cJAZJFuture, wenShiAZJFuture).get(11 ,TimeUnit.MINUTES);
            //获取结果
            result.setYouPinResult((List<Map<String, Object>>) youPinFuture.get());
            result.setAiDouResult((List<Map<String, Object>>) aiDouFuture.get());
            result.setQianLianYPResult((List<Map<String, Object>>) qianLianYPFuture.get());
            result.setErSQLYPResult((List<Map<String, Object>>) erSYPFuture.get());
            result.setRenRZResult((List<Map<String, Object>>) renRZFuture.get());
            result.setErSRRZResult((List<Map<String, Object>>) erSRRZFuture.get());
            result.setLingLResult((List<Map<String, Object>>) lLFuture.get());
            result.setGuangCLLResult((List<Map<String, Object>>) gCLingLFuture.get());
            result.setAiZJResult((List<Map<String, Object>>) aiZJLingLFuture.get());
            result.setChangJAZJResult((List<Map<String, Object>>) cJAZJFuture.get());
            result.setWenSAZJResult((List<Map<String, Object>>) wenShiAZJFuture.get());
        }catch (Exception e){
            logger.error("获取数据时发生异常~~~~~~~~~~~~", e);
        }
        return result;
    }

    //更新额外的逾期数据
    //@Scheduled(fixedRate = 60 * 60 * 24000)
    //每晚上10点执行一次
    //@Scheduled(cron = "0 0 22 * * ?")
    //@Scheduled(cron = "0 0 0 * * ?")  //每天0点执行一次
    public MultiPlatfromResult getOverdue() {
        MultiPlatfromResult result = new MultiPlatfromResult();
        //从数据库获取
        QueryWrapper<RequestHeard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",1);
        RequestHeard requestHeard = requestMapper.selectOne(queryWrapper);
        String renRZYQCookie = requestHeard.getRenrzyqcookie();
        String lLCookie = requestHeard.getLinglcookie();
        String lingLToken = requestHeard.getLingltoken();
        String gCLLCookie = requestHeard.getGclinglcookie();
        String gCLLToken = requestHeard.getGclingltoken();
        String aizjtk = requestHeard.getAzjtk();
        String cJAZJtk = requestHeard.getCjazjtk();
        String wsAZJtk = requestHeard.getWsazjtk();
        logger.info("更新三个平台的逾期数据~~:");
        //更新人人租逾期 数据
        CompletableFuture<Object> renRZOverdueFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("人人租平台 逾期 数据...");
            return renRZuService.getOverdue(renRZYQCookie);
        });
        //更新零零逾期 数据
        CompletableFuture<Object> lLOverdueFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("零零平台 逾期 数据...");
            return lingLService.getOverdue(lLCookie, lingLToken);
        });
        //更新广创零零逾期数据
        CompletableFuture<Object> gCLingLOverdueFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("广创零零平台 逾期 数据...");
            return gCLingLService.getOverdue(gCLLCookie, gCLLToken);
        });
        //更新爱租机逾期数据
        CompletableFuture<Object> aiZJOverdueFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("爱租机平台 逾期 数据...");
            return aizujiService.getOverdue(aizjtk);
        });
        //更新长久爱租机逾期数据
        CompletableFuture<Object> cJAZJOverdueFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("长久爱租机平台 逾期 数据...");
            return changJiuAZJService.getOverdue(cJAZJtk);
        });
        //更新稳实爱租机逾期数据
        CompletableFuture<Object> wenShiAZJOverdueFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("稳实爱租机平台 逾期 数据...");
            return wenShiAZJService.getOverdue(wsAZJtk);
        });
        try {
            CompletableFuture.allOf(renRZOverdueFuture, lLOverdueFuture, gCLingLOverdueFuture, aiZJOverdueFuture, cJAZJOverdueFuture, wenShiAZJOverdueFuture).get(6 ,TimeUnit.MINUTES);
            //获取结果
            result.setRenRZResult((List<Map<String, Object>>) renRZOverdueFuture.get());
            result.setLingLResult((List<Map<String, Object>>) lLOverdueFuture.get());
            result.setGuangCLLResult((List<Map<String, Object>>) gCLingLOverdueFuture.get());
            result.setAiZJResult((List<Map<String, Object>>) aiZJOverdueFuture.get());
            result.setChangJAZJResult((List<Map<String, Object>>) cJAZJOverdueFuture.get());
            result.setWenSAZJResult((List<Map<String, Object>>) wenShiAZJOverdueFuture.get());

        }catch (Exception e){
            logger.error("获取数据时发生异常~~~~~~~~~~~~", e);
        }
        return result;
    }

    //获取优品风控所有订单列表详情
    //@Scheduled(fixedRate = 3 * 60 * 1000)  //每5分钟执行一次
    public List<Map<String, Object>> getOrderList() {
        //从数据库获取
        try {
            QueryWrapper<RequestHeard> queryWrapper = new QueryWrapper<>();
            RequestHeard requestHeard = requestMapper.selectOne(queryWrapper);
            String accesstoken = requestHeard.getAccesstoken();
            String authorization = requestHeard.getAuthorization();
            List<Map<String, Object>> result = ypRiskService.getOrderssList(accesstoken, authorization);
            return result;
        } catch (Exception e) {
            logger.error("获取 优品风控 所有订单列表详情失败");
            return null;
        }
    }

    //定时查询风控结果、
    //@Scheduled(fixedRate = 10 * 60 * 1000)  //每5分钟执行一次
    public void scheduledQueryApproval() {
        logger.info("开始执行风控授信结果定时查询任务");
        try {
            //查询想要轮询的风控记录
            QueryWrapper<RiskApprovil> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNull("approval_status")
                    .or()
                    .eq("approval_status", "3");
            List<RiskApprovil> riskApprovals = riskApprovilMapper.selectList(queryWrapper);
            logger.info("查询到的风控记录有：{}", riskApprovals.size());
            for (RiskApprovil riskApprovil : riskApprovals) {
                try {
                    String creditId = riskApprovil.getCreditId();
                    youPinService.queryApproval(creditId);

                }catch (Exception e){
                    logger.error("查询风控授信结果失败,creditId : {}", riskApprovil.getCreditId(),e);
                }
            }
            logger.info("风控授信结果定时查询任务执行完成");
        } catch (Exception e) {
            logger.error("风控授信结果定时查询任务失败");
        }
    }
}
